﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Data;
using MySql.Data.MySqlClient;
using System.Data.SqlClient;

namespace com.tiyma.components
{
    public class SiteMapManager
    {
        public void CreateSiteMap()
        {
            XmlDocument t_xml_doc = new XmlDocument();
            XmlDeclaration t_xml_dec= t_xml_doc.CreateXmlDeclaration("1.0", "UTF-8","");
            t_xml_doc.AppendChild(t_xml_dec);
            XmlElement t_root_ele = t_xml_doc.CreateElement("urlset");
            t_root_ele.SetAttribute("xmlns", "http://www.google.com/schemas/sitemap/0.84");
            t_xml_doc.AppendChild(t_root_ele);
            //创建导航栏目
            string[] t_nav_url_arr = new string[] { "http://www.tiyma.com/bookList/wx/", "http://www.tiyma.com/bookList/xx/", "http://www.tiyma.com/bookList/kh/", "http://www.tiyma.com/bookList/xh/", "http://www.tiyma.com/bookList/mh/", "http://www.tiyma.com/bookList/wy/", "http://www.tiyma.com/bookList/yq/", "http://www.tiyma.com/bookList/np/", "http://www.tiyma.com/bookList/ls/", "http://www.tiyma.com/bookList/mz/", "http://www.tiyma.com/bookList/ds/", "http://www.tiyma.com/bookList/mw/", "http://www.tiyma.com/bookList/jb/", "http://www.tiyma.com/bookList/xd/", "http://www.tiyma.com/bookList/tr/", "http://www.tiyma.com/bookList/qt/" };

            t_root_ele = CreateSiteMapUrl("http://www.tiyma.com", DateTime.Now.ToString("yyyy-MM-dd"), "always", "1.0", t_root_ele, t_xml_doc);

            foreach (string t_nav_url in t_nav_url_arr)
            {
                t_root_ele = CreateSiteMapUrl(t_nav_url, DateTime.Now.ToString("yyyy-MM-dd"), "always", "1.0", t_root_ele,t_xml_doc);
            }

            List<BookInfo> t_book_hot_list = GetHotBookList();
            if (t_book_hot_list != null && t_book_hot_list.Count > 0)
            {
                foreach (BookInfo t_book in t_book_hot_list)
                {
                    t_root_ele = CreateSiteMapUrl(string.Format("http://www.tiyma.com/book/{0}/",  t_book.BookId), t_book.LastUpdateTime.ToString("yyyy-MM-dd"), "daily", "1.0", t_root_ele, t_xml_doc);
                }
            }

            List<BookInfo> t_book_update_list = GetLastUpdateBook(120);
            bool t_is_exist = false;
            if (t_book_update_list != null && t_book_update_list.Count > 0)
            {
                foreach (BookInfo t_update_book in t_book_update_list)
                {
                    t_is_exist = false;
                    foreach (BookInfo t_book in t_book_hot_list)
                    {
                        if (t_update_book.BookId.Equals(t_book.BookId))
                        {
                            t_is_exist = true;
                            break;
                        }
                    }
                    if (t_is_exist)
                        continue;

                    t_root_ele = CreateSiteMapUrl(string.Format("http://www.tiyma.com/book/{0}/", t_update_book.BookId), t_update_book.LastUpdateTime.ToString("yyyy-MM-dd"), "always", "1.0", t_root_ele, t_xml_doc);
                }
            }

            t_xml_doc.Save(System.IO.Path.Combine(AppConfig.SiteMapPath, "sitemap.xml"));

            //创建所有小说站点地图
            t_book_hot_list.AddRange(t_book_update_list);

            List<BookInfo> t_all_book_list = GetAllBook();
            if (t_all_book_list != null && t_all_book_list.Count > 0)
            {
                XmlDocument t_xml_doc2 = new XmlDocument();
                XmlDeclaration t_xml_dec2 = t_xml_doc2.CreateXmlDeclaration("1.0", "UTF-8", "");
                t_xml_doc2.AppendChild(t_xml_dec2);
                XmlElement t_root_ele2 = t_xml_doc2.CreateElement("urlset");
                t_root_ele2.SetAttribute("xmlns", "http://www.google.com/schemas/sitemap/0.9");
                t_xml_doc2.AppendChild(t_root_ele2);
                int index = 0;
                foreach (BookInfo t_all_book in t_all_book_list)
                {
                    t_is_exist = false;
                    foreach (BookInfo t_book in t_book_hot_list)
                    {
                        if (t_all_book.BookId.Equals(t_book.BookId))
                        {
                            t_is_exist = true;
                            break;
                        }
                    }
                    if (t_is_exist)
                        continue;
                    index++;
                    if (index % 200 == 0)
                    {
                        t_xml_doc2.Save(System.IO.Path.Combine(AppConfig.SiteMapPath, string.Format("sitemap{0}.xml",(index/200))));
                        t_xml_doc2 = new XmlDocument();
                        t_xml_dec2 = t_xml_doc2.CreateXmlDeclaration("1.0", "UTF-8", "");
                        t_root_ele2 = t_xml_doc2.CreateElement("urlset");
                        t_root_ele2.SetAttribute("xmlns", "http://www.google.com/schemas/sitemap/0.9");
                        t_xml_doc2.AppendChild(t_xml_dec2);
                        t_xml_doc2.AppendChild(t_root_ele2);
                       
                    }
                    t_root_ele2 = CreateSiteMapUrl(string.Format("http://www.tiyma.com/book/{0}/",  t_all_book.BookId), t_all_book.LastUpdateTime.ToString("yyyy-MM-dd"), "always", "0.8", t_root_ele2, t_xml_doc2);
                }
                t_xml_doc2.Save(System.IO.Path.Combine(AppConfig.SiteMapPath, string.Format("sitemap{0}.xml", (index % 200==0?index/200:index/200+1))));
            }
        }

        private XmlElement CreateSiteMapUrl(string i_loc, string i_lastmod, string i_changefreq, string i_priority, XmlElement i_xml_ele, XmlDocument i_xml_doc)
        {
            XmlElement t_nav_url_ele = i_xml_doc.CreateElement("url");

            XmlElement t_nav_url_loc = i_xml_doc.CreateElement("loc");
            t_nav_url_loc.InnerText = i_loc;

            XmlElement t_nav_url_lastmod = i_xml_doc.CreateElement("lastmod");
            t_nav_url_lastmod.InnerText = i_lastmod;

            XmlElement t_nav_url_changefreq = i_xml_doc.CreateElement("changefreq");
            t_nav_url_changefreq.InnerText = i_changefreq;

            XmlElement t_nav_url_priority = i_xml_doc.CreateElement("priority");
            t_nav_url_priority.InnerText = i_priority;


            t_nav_url_ele.AppendChild(t_nav_url_loc);
            t_nav_url_ele.AppendChild(t_nav_url_lastmod);
            t_nav_url_ele.AppendChild(t_nav_url_changefreq);
            t_nav_url_ele.AppendChild(t_nav_url_priority);

            i_xml_ele.AppendChild(t_nav_url_ele);

            return i_xml_ele;
        }

        /// <summary>
        /// 获取小说列表失败
        /// </summary>
        /// <returns></returns>
        public List<BookInfo> GetAllBook()
        {
            string t_str_sql = "select top 10000 bookId,siteId, lastUpdateTime from tbbook order by lastupdatetime desc ";
            List<BookInfo> t_list = null;
            try
            {
                DataSet t_ds = DataBaseManager.Query(t_str_sql);

                if (t_ds != null && t_ds.Tables.Count > 0 && t_ds.Tables[0].Rows.Count > 0)
                {
                    BookInfo t_book = null;

                    t_list = new List<BookInfo>();

                    foreach (DataRow t_dr in t_ds.Tables[0].Rows)
                    {
                        t_book = new BookInfo();

                        t_book.BookId = t_dr["bookId"].ToString();
                        t_book.LastUpdateTime = t_dr["lastUpdateTime"] == DBNull.Value ? DateTime.Now : Convert.ToDateTime(t_dr["lastUpdateTime"].ToString());
                        t_book.SiteId = Convert.ToInt32(t_dr["siteId"].ToString());

                        t_list.Add(t_book);
                    }
                }
                return t_list;
            }
            catch (Exception ex)
            {
                throw new DataException("获取小说列表失败", ex);
            }
        }


        /// <summary>
        /// 获取需要更新章节的图书列表
        /// </summary>
        /// <returns></returns>
        public List<BookInfo> GetHotBookList()
        {
            string t_str_sql = "select top 1000 a.bookId,siteId, lastUpdateTime from tbbook a,tbbookclick b where a.bookId=b.bookId order by b.clickcount desc ";
      

            List<BookInfo> t_list = null;
            try
            {
                DataSet t_ds = DataBaseManager.Query(t_str_sql);

                if (t_ds != null && t_ds.Tables.Count > 0 && t_ds.Tables[0].Rows.Count > 0)
                {
                    BookInfo t_book = null;

                    t_list = new List<BookInfo>();

                    foreach (DataRow t_dr in t_ds.Tables[0].Rows)
                    {
                        t_book = new BookInfo();
                
                        t_book.BookId = t_dr["bookId"].ToString();
                        t_book.LastUpdateTime = t_dr["lastUpdateTime"] == DBNull.Value ? DateTime.Now : Convert.ToDateTime(t_dr["lastUpdateTime"].ToString());
                        t_book.SiteId = Convert.ToInt32(t_dr["siteId"].ToString());
                     
                        t_list.Add(t_book);
                    }
                }
                return t_list;
            }
            catch (Exception ex)
            {
                throw new DataException("获取需要更新章节的图书列表失败", ex);
            }
        }

        /// <summary>
        /// 获取最新更新小说
        /// </summary>
        /// <param name="i_count"></param>
        /// <returns></returns>
        public List<BookInfo> GetLastUpdateBook(int i_count)
        {
            string t_str_sql = string.Format("select top {0} t.bookid,t.lastupdatetime,t.siteId from tbbook t order by lastupdatetime desc ",i_count);
            

            BookInfo t_book = null;

            List<BookInfo> t_list = null;
            try
            {
                 using (SqlConnection t_connection = new SqlConnection(AppConfig.SqlConnectionString))
                {
                    using (SqlCommand t_cmd = new SqlCommand(t_str_sql, t_connection))
                    {

                        t_cmd.CommandTimeout = 600;
                        t_connection.Open();
                        using (SqlDataReader reader = t_cmd.ExecuteReader(CommandBehavior.CloseConnection))
                        {
                            t_list = new List<BookInfo>();

                            while (reader.Read())
                            {
                                t_book = new BookInfo();
                                t_book.BookId = reader["bookid"].ToString();

                                t_book.SiteId = Convert.ToInt32(reader["siteId"].ToString());

                                t_book.LastUpdateTime = reader["lastupdatetime"] == DBNull.Value ? DateTime.Now.AddHours(-1) : Convert.ToDateTime(reader["lastupdatetime"].ToString());

                                t_list.Add(t_book);
                            }
                        }
                    }
                }

                return t_list;
            }
            catch (Exception ex)
            {
                throw new DataException("获取最新更新小说失败", ex);
            }

        }
    }
}
